package cn.zfgc.jfinal.controller;

import cn.zfgc.jfinal.core.Controller;
import cn.zfgc.jfinal.entity.ReturnDataDO;
import cn.zfgc.jfinal.kit.PathKit;
import com.github.binarywang.utils.qrcode.QrcodeUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

/**
 * Created by wangwang on 2017/5/24 0024.
 */
public class Qrcode extends Controller {
    private static boolean flag = false;
    private static int count = 0;

    public void doQrcodeCreate() {
        if (flag || count == 0) {
            String filePath = "/qrcode/" + count + ".jpg";
            String content = this.getRequest().getRequestURL().toString().replaceAll(this.getRequest().getRequestURI().toString(), "").concat("/signPage.html");
            create(filePath, content);
            flag = false;
            renderJson(ReturnDataDO.returnJson(0, "改变", filePath));
            return;
        }
        renderJson(ReturnDataDO.returnJson(1, "未改变", ""));
    }

    private void create(String filePath, String content) {
        byte[] bytes = QrcodeUtils.createQrcode(content, 800, null);
        count++;
        filePath = PathKit.getWebRootPath() + filePath;
        try {
            new File(filePath).createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Path newfile = FileSystems.getDefault().getPath(filePath);
        try {
            Files.write(newfile, bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void doQrcodeChange() {
        flag = true;
        renderJson(ReturnDataDO.returnJson(0, "", ""));
    }
}
